package com.example.liuke.guangguang.untils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

/**
 * Created by liuke on 2017/11/21.   这是做usb的usb
 */

public class getfilestwo {
    /**
     *  
     *      * 从usb获取图片资源
     *      * @return 
     *      
     */
    //  /mnt/usb_storage
    public static ArrayList<String> getImagePathFromSD(Activity context, String filename) {
        //String filePath = "/mnt/usb_storage/" + filename;
        String filePath = "/mnt/mmcblk1/mmcblk1p1/" + filename;
        // 图片列表  
        ArrayList<String> imagePathList = new ArrayList<String>();
        // 得到该路径文件夹下所有的文件  
        File fileAll = new File(filePath);
        if (!fileAll.exists()) {
            fileAll.mkdirs();
        }
        File[] files = fileAll.listFiles();
        if (files == null || files.length == 0) {
            Toast.makeText(context, "目标文件中没有文件，请查看USB设备中的文件名是否正确！", Toast.LENGTH_SHORT).show();
        }else {
            // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件  
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                if (checkIsImageFile(file.getPath())) {
                    imagePathList.add(file.getPath());
                }
            }
        }
        // 返回得到的图片列表  
        return imagePathList;
    }

    /**
     *  
     *      * 检查扩展名，得到图片格式的文件 
     *      * @param fName  文件名 
     *      * @return 
     *      
     */
    @SuppressLint("DefaultLocale")
    private static boolean checkIsImageFile(String fName) {
        boolean isImageFile = false;
        // 获取扩展名  
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
        if (FileEnd.equals("jpg") || FileEnd.equals("png") || FileEnd.equals("gif")
                || FileEnd.equals("jpeg") || FileEnd.equals("bmp") || FileEnd.equals("mp4")) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }



    /**
     * 普通的文件复制方法,这个可以写监听的过程，但是时间上没有下面的快
     *
     * @param fromFile 源文件
     * @param toFile   目标文件
     * @throws FileNotFoundException 未找到文件异常
     */
    public void fileCopyNormal(File fromFile, File toFile) throws FileNotFoundException {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(fromFile));
            outputStream = new BufferedOutputStream(new FileOutputStream(toFile));
            byte[] bytes = new byte[1024];
            int i;
            //读取到输入流数据，然后写入到输出流中去，实现复制
            while ((i = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 复制文件
     *
     * @param srcPath  : 源文件全路径
     * @param destPath : 目标文件全路径
     * @return
     */
    public static long copyFile(Activity context,String srcPath, String destPath) {
        try {
            int position = destPath.lastIndexOf(File.separator);
            String dir = destPath.substring(0, position);
            String newFileName = destPath.substring(position + 1);
            final File cacheDir = new File(dir);
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }
            return copyFile(context,new File(srcPath), new File(dir), newFileName);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 复制文件(以超快的速度复制文件)
     *
     * @param srcFile     源文件File
     * @param destDir     目标目录File
     * @param newFileName 新文件名
     * @return 实际复制的字节数，如果文件、目录不存在、文件为null或者发生IO异常，返回-1
     */
    @SuppressWarnings("resource")
    public static long copyFile(final Activity activity,final File srcFile, final File destDir, String newFileName) {
        long copySizes = 0;
        if (!srcFile.exists()) {
            Toast.makeText(activity,"源文件不存在",Toast.LENGTH_SHORT).show();
            System.out.println("源文件不存在");
            copySizes = -1;
        } else if (!destDir.exists()) {
            Toast.makeText(activity,"目标目录不存在",Toast.LENGTH_SHORT).show();
            System.out.println("目标目录不存在");
            copySizes = -1;
        } else if (newFileName == null) {
            Toast.makeText(activity,"文件名为空",Toast.LENGTH_SHORT).show();
            System.out.println("文件名为null");
            copySizes = -1;
        } else {
            FileChannel fcin = null;
            FileChannel fcout = null;
            try {
                //.getChannel()返回文件通道对象
                //得到fileInputStream的文件通道
                fcin = new FileInputStream(srcFile).getChannel();
                //得到fileOutputStream的文件通道
                fcout = new FileOutputStream(new File(destDir, newFileName)).getChannel();
                long size = fcin.size();
                long i =fcin.transferTo(0, fcin.size(), fcout);
                System.out.println("shifoushishi    :  "+i);
                copySizes = size;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fcin != null) {
                        fcin.close();
                    }
                    if (fcout != null) {
                        fcout.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return copySizes;
    }

    /**
     * 获取文件名
     *
     * @param path
     *            全路径
     * @return
     */
    public static String getFileName(String path) {
        if (!TextUtils.isEmpty(path)) {
            return path.substring(path.lastIndexOf(File.separator) + 1);
        }
        return "";
    }

    /**
     * 获取后缀名
     *
     * @param path
     *            全路径
     * @return
     */
    public static String getFileExtName(String path) {
        String ext = "";
        if ((path != null) && (path.length() > 0)) {
            int dot = path.lastIndexOf('.');
            if ((dot > -1) && (dot < (path.length() - 1))) {
                ext = path.substring(dot + 1);
            }
        }
        return ext;
    }


    /**
     * 删除文件夹内所有文件
     *
     * @param delpath
     *            delpath path of file
     * @return boolean the result
     */
    public static boolean deleteAllFile(String delpath) {
        try {
            // create file
            final File file = new File(delpath);

            if (!file.isDirectory()) {
                file.delete();
            } else if (file.isDirectory()) {

                final String[] filelist = file.list();
                final int size = filelist.length;
                for (int i = 0; i < size; i++) {

                    // create new file
                    final File delfile = new File(delpath + "/" + filelist[i]);
                    if (!delfile.isDirectory()) {
                        delfile.delete();
                    } else if (delfile.isDirectory()) {
                        // digui
                        deleteFile(delpath + "/" + filelist[i]);
                    }
                }
                file.delete();
            }
        } catch (Exception ex) {

            return false;
        }
        return true;
    }
    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    public static boolean deleteFile(String filePath) {


        if (!TextUtils.isEmpty(filePath)) {
            final File file = new File(filePath);

            if (file.exists()) {
                return file.delete();
            }
        }
        return false;
    }

}
